import logging

logger = logging.getLogger("KVO")


class NSObject(object):
    """ provides for a notify/observer class to make it easier to write UI"""

    def __init__(self):
        self.__dict__['_observers'] = {}

    def __setattr__(self, attrname, value):
        # set the attribute
        self.__dict__[attrname] = value
        # if the attribute triggers a notification
        self.didChangeValue(attrname, value)

    def addObserver(self, observer, attrname):
        observers = self.__dict__['_observers'].get(attrname)
        if observers is None:
            observers = []
            self.__dict__['_observers'][attrname] = observers
        if not observer in observers:
            observers.append(observer)
            # and call back
            observer(self, attrname, self.__dict__.get(attrname, None))

    def removeObserver(self, observer):
        for attrname in self.__dict__['_observers']:
            try:
                self._observers[attrname].remove(observer)
            except ValueError:
                pass

    def didChangeValue(self, attrname, value=None):
        logger.debug("didChangeValue %s %s", attrname, value)
        if value is None:
            value = self.__dict__.get(attrname, None)
        for observer in self.__dict__['_observers'].get(attrname, []):
            observer(self, attrname, value)

